/** @format */

const fs = require("fs");
const { resolve } = require("path");
const express = require("express");
const os = require("os")
const { createServer: createViteServer } = require("vite");
const port = process.env.port || process.env.npm_config_port || process.env.NODE_ENV === 'dev' ? 3000  : 9099// 端口


const JSONFILE = './local.bak.json';
const MSG = {
  success: {
    code: '0',
    message: 'success'
  }
}


async function createServer() {
  const app = express();

  const vite = await createViteServer({
    server: { middlewareMode: "ssr" },
  });

  // use vite's connect instance as middleware
  app.use(vite.middlewares);
  app.use(express.json());
  app.use(express.urlencoded({ extended: false }));

  app.use("/getSysList", async (req, res) => {
    console.log(32, req.originalUrl)
    const data = readFile().map(item => item.sys)
    res.json({
      ...MSG.success,
      data
    });
  });


  app.use("/getJsonData", async (req, res) => {
    const { pageNum: page, pageSize: size, _t, ...rest} = req.query
    let data = readFile(), total = data.length
   
    if (Object.keys(rest).length) {
      resData = filterData(rest, data), total = resData.length;
      resData = resData.splice((page - 1) * size, size)
    } else {
      resData = data.splice((page - 1) * size, size)
    }
   
    res.json({
      ...MSG.success,
      data: resData,
      total
    });
  });

  app.use("/saveJsonData", async (req, res) => {
    const data = JSON.stringify(req.body);
    // const data = Buffer.from(JSON.stringify(res.body))
    // fs.copyFile('./public/local.json', './local.bak.json', err => {
    //   if (err) console.log('something err.')
    //   else  console.log('copry file success.')
    // })
    // let origin = fs.createReadStream('./public/local.json')
    // let out = fs.createWriteStream('./local.bak.json')
    // origin.pipe(out)
    save(data)
    console.log('save success.')
    res.json(MSG.success);
  });

  app.use("/delJsonData", async (req, res) => {
    const { id } = req.body
    const bak = readFile()
    bak.splice(bak.findIndex(id => id), 1)
    writeContxt(bak);
    res.json(MSG.success)
  })

  app.use("/editJsonData", async (req, res) => {
    const { id, _t, ...rest } = req.body
    const bak = readFile()
    let index = bak.findIndex(item => item.id === id)
    bak[index] = { id, ...rest }
    writeContxt(bak);
    res.json(MSG.success)
  })

  app.use("/", async (req, res) => {
    const { originalUrl: url } = req;
    try {
      let temp = fs.readFileSync(resolve(__dirname, "./index.html"), "utf-8");

      temp = await vite.transformIndexHtml(url, temp);

      const { render } = await vite.ssrLoadModule("./src/entry-server.js");

      const appHtml = await render(url);

      const html = temp.replace(`<!--ssr-outlet-->`, appHtml);

      res.status(200).set({ "Content-Type": "text/html" }).end(html);
    } catch (e) {
      vite.ssrFixStacktrace(e);
      console.error(e);
      res.status(500).end(e.message);
    }
  });

  app.listen(port, () => console.log(`server is running at ${port}...`));
}

createServer();

function save(data) {
  data = JSON.parse(data);
  const bak = readFile()
  bak.unshift({id: bak.length + 1, ...data})
  writeContxt(bak)
}

function readFile() {
  return  JSON.parse(fs.readFileSync(resolve(__dirname, JSONFILE), 'utf-8'))
}

function writeContxt(data) {
  const o = JSON.stringify(data)
   // os.EOL 换行符
   fs.writeFileSync(JSONFILE, o + os.EOL);
}

function filterData(field, data) {
  let res = data
  Object.keys(field).forEach((item) => {
    if (field[item]) {
      res = res.filter(f => f[item] == field[item])
    }
  })
  return res;
}